#include <jni.h>
#include <string>
#include <android/log.h>
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"LOG_TAG",__VA_ARGS__);
using namespace std;

void dyTest(){
    LOGE("dyTest")

}

//动态注册   调用线程的话 要注意线程的切换 _vm->AttachCurrentThread()

JavaVM *_vm;

static const JNINativeMethod method[] = {
        {"test","()V",(void *)dyTest}
};
static const char *mClassName = "com/example/nativelib/ExampleInstrumentedTest";
int JNI_OnLoad(JavaVM *vm,void *re){
    LOGE("JNI_OnLoad");
    _vm = vm;

    //获得JNIEnv
    JNIEnv *env = nullptr;
    //小于0失败 等于0成功
    int i = vm->GetEnv((void **)&env,JNI_VERSION_1_6);
    if (i != JNI_OK){
        return -1;
    }
    //获得class对象
    jclass jcls = env->FindClass(mClassName);
    //注册
    env->RegisterNatives(jcls,method,sizeof(method)/sizeof(JNINativeMethod));
    return JNI_VERSION_1_6;
}



//这些都是静态注册
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_nativelib_NativeLib_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_nativelib_ExampleInstrumentedTest_passObject(JNIEnv *env, jobject thiz,
                                                              jobject bean,jstring msg) {
    const char *str = env->GetStringUTFChars(msg,nullptr);

    //反射调用java方法
    jclass beanClass = env->GetObjectClass(bean);
    //找到要调用的方法
    //参数3 签名详细看课件  get
    jmethodID getI = env->GetMethodID(beanClass,"getI","()I");

    //调用
    jint i = env->CallIntMethod(bean,getI);
    LOGE("C++调用 JAVA方法%d",i);

    //set
    jmethodID setI = env->GetMethodID(beanClass,"setI","(I)V");

    //创建java字符串
    jstring str1 = env->NewStringUTF("我水水水水");
    jmethodID printInfo = env->GetStaticMethodID(beanClass,"printInfo", "(Ljava/lang/String;)V");
    env->CallStaticVoidMethod(beanClass,printInfo,str1);

    //设置值
    jfieldID jfieldId = env->GetFieldID(beanClass,"i", "I");
    env->SetIntField(bean,jfieldId,200);

    env->DeleteLocalRef(str1);
    env->ReleaseStringUTFChars(msg,str);
}
